package com.cheng.controller;

import ch.qos.logback.core.util.FileUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.cheng.service.FaceService.TeacherService;
import com.cheng.utli.RedisUtil;
import com.cheng.utli.Utils;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import static com.cheng.controller.Constant.*;

@Controller
@RequestMapping(value = "/Teacher")
public class TeacherController {
    @Autowired
    private TeacherService teacherService;

    @Autowired
    private RedisUtil redisUtil;

    private static final Logger logger = LoggerFactory.getLogger(TeacherController.class);
    /**
     * 教师添加班级操作
     * return cid 班级编号
     * */
    @RequestMapping(value = "/addClass" ,produces="text/html;charset=UTF-8")
    @ResponseBody
    public JSONObject addClass(HttpSession session, HttpServletRequest request){
        JSONObject returnObj = new JSONObject();
        //获得教师openid
        String openId = getSession(session);
        String name = request.getParameter("name");
        String introduce = request.getParameter("introduce");

        if(Utils.isBlank(name)){
            return setReturnObjInfo("-100","没有填写班级姓名");
        }

        if(Utils.isBlank(introduce)){
            return setReturnObjInfo("-100","没有填写班级简介");
        }

        if(Utils.isBlank(openId)){
            return setReturnObjInfo("noLogin","noLogin");
        }

        HashMap<String,String> classInfo = new HashMap<String,String>();
        classInfo.put("openId",openId);
        classInfo.put("name",name);
        classInfo.put("introduce",introduce);

        String cid =teacherService.addClass(classInfo);
        returnObj.put("cid",cid);
        returnObj.put("resCode",100);
        return  returnObj;
    }


    /**
     * 开启签到功能，
     * */
    @RequestMapping(value = "/startSignIn" ,produces="text/html;charset=UTF-8")
    @ResponseBody
    public JSONObject startSignIn(HttpSession session, HttpServletRequest request){
        JSONObject returnObj = new JSONObject();
        //获得老师openid
        String openId = getSession(session);
        if(Utils.isBlank(openId)){
            return setReturnObjInfo("-100","没有登录");
        }

        //获得签到类型  1.开启人脸签到 2.开启随机密码签到  3.开启九宫格签到
        String type = request.getParameter("type");
        String cid = request.getParameter("cid");
        String typeParam = "1,2,3";
        if(!(typeParam).contains(type)){
            return setReturnObjInfo("failParam","参数错误");
        }
        logger.error(redisUtil.formatRedisKey(CLASS_SIGN_KEY,cid));
        if(redisUtil.exists(redisUtil.formatRedisKey(CLASS_SIGN_KEY,cid))){
            returnObj.put("resCode","noTimeOut");
            returnObj.put("password",redisUtil.getString(redisUtil.formatRedisKey(CLASS_SIGN_KEY_PASSWORD,cid)));
            return returnObj;
        }


        //设置签到时间
        String time = request.getParameter("time");
        //获得开启签到人的经度纬度
        Double latitude = Double.valueOf(request.getParameter("latitude"));
        Double longitude = Double.valueOf(request.getParameter("longitude"));
        JSONObject location = new JSONObject();
        location.put("latitude",latitude);
        location.put("longitude",longitude);

        //单位转换
        int date = Integer.parseInt(time)*60;


        //得到当前时间五分钟后的时间戳
        Calendar beforeTime = Calendar.getInstance();
//        beforeTime.add(Calendar.MINUTE, Integer.parseInt(time));
        beforeTime.add(Calendar.MINUTE, +300);
        Date beforeDate = beforeTime.getTime();
        long time1 = beforeDate.getTime();

        JSONObject info = new JSONObject();
        info.put("time",time1);
        info.put("type",type);
        //加入redis缓存  签到时间，签到类型
        redisUtil.set(redisUtil.formatRedisKey(CLASS_SIGN_KEY,cid),info.toString(), 300L);
        logger.error(redisUtil.formatRedisKey(CLASS_SIGN_KEY,cid));

        redisUtil.set(redisUtil.formatRedisKey(CLASSLOCATION,cid),location.toString(),(long) 300L);
        //设置密码缓存
        String passWord ="";
        //随机生成五位数密码
        if(type.equals("2")){
            passWord = Utils.randomString().substring(0,5);
        }
        //九宫格密码
        if(type.equals("3")){
            passWord = request.getParameter("passWord");
        }
        redisUtil.set(redisUtil.formatRedisKey(CLASS_SIGN_KEY_PASSWORD,cid),passWord,(long) date);

        returnObj = teacherService.startSignIn(cid,type);
        returnObj.put("password",passWord);
        //删除缓存
        String key = redisUtil.formatRedisKey(TEACHER_GET_SIGN_INFO,cid,openId);
        redisUtil.remove(key);
        return returnObj;
    }

    /**
     * 老师查询当前班级签到记录和次数
     * */
    @RequestMapping(value = "/teacherqueryClassSignInInfo" ,produces="text/html;charset=UTF-8")
    @ResponseBody
    public JSONObject queryClassSignInCount(HttpSession session, HttpServletRequest request) throws ParseException {
        JSONObject returnObj = new JSONObject();

        String openId = getSession(session);
        if(Utils.isBlank(openId)){
            return setReturnObjInfo("-100","没有登录");
        }

        String cid = request.getParameter("cid");

        String key = redisUtil.formatRedisKey(TEACHER_GET_SIGN_INFO,cid,openId);

        JSONObject signInfo =  redisUtil.getJson(key);

        if(signInfo ==null){
            signInfo = teacherService.queryByCidSignIn(cid);
            //得到的数据存入缓存
            redisUtil.set(key, signInfo.toString(), 600L);
        }
        returnObj.put("suc","100");
        returnObj.put("signInfo",signInfo);
        returnObj.put("cid",cid);
        return returnObj;
    }

    /**
     * 教师根据number和cid获得某一次具体的签到信息
     * */
    @RequestMapping(value = "/queryClassDetailSignInfo" ,produces="text/html;charset=UTF-8")
    @ResponseBody
    public JSONObject queryClassDetailSignInfo(HttpSession session, HttpServletRequest request){
        JSONObject returnObj = new JSONObject();

        String openId = getSession(session);
        if(Utils.isBlank(openId)){
            return setReturnObjInfo("-100","没有登录");
        }
        String cid = request.getParameter("cid");
        String number = request.getParameter("number");

        String key = redisUtil.formatRedisKey(TEACHER_GET_ONE_DETAIL_SIGN_INFO,cid,number);

        JSONObject signDetailInfo = redisUtil.getJson(key);

        if(signDetailInfo ==null){
            signDetailInfo = teacherService.queryClassDetailSignInfo(cid,number);
            redisUtil.set(key, signDetailInfo.toString(), 600L);
        }
        logger.info("得到的具体签到信息"+signDetailInfo.toString());
        returnObj.put("suc",100);
        returnObj.put("signDetailInfo",signDetailInfo);
        return returnObj;
    }


    /**
     * 教师点击班级页面,同时显示是否存在未处理的请假信息
     * */
    @RequestMapping(value = "/getTeacherCreateClass" ,produces="text/html;charset=UTF-8")
    @ResponseBody
    public JSONObject getTeacherCreateClass(HttpSession session, HttpServletRequest request){
        JSONObject returnObj = new JSONObject();

        String openId = getSession(session);

        if(Utils.isBlank(openId)){
            return setReturnObjInfo("-100","没有登录");
        }
        JSONObject result = teacherService.getTeacherCreateClass(openId);
        returnObj.put("classList",result.getString("classList"));

        //判断班级的cid是否存在未审批的请假
        Boolean flag = false;
        String tid = result.getString("tid");
        String key = redisUtil.formatRedisKey(TEACHER_GET_LEAVE_INFO,openId);

        JSONObject LeaveInfo = redisUtil.getJson(key);

        if(LeaveInfo ==null){
            LeaveInfo = teacherService.checkLeaveState(openId);
        }
        if(LeaveInfo !=null){
            if(LeaveInfo !=null) {
                redisUtil.set(key, LeaveInfo.toString(), 50L);
            }
            flag = true;
        }
        result.put("flag",flag);
        result.put("tid",tid);

        return result;
    }

    /**
     * 教师进入请假页面
     * */
    @RequestMapping(value = "/showLeaveInfo" ,produces="text/html;charset=UTF-8")
    @ResponseBody
    public JSONObject showLeaveInfo(HttpSession session, HttpServletRequest request) throws ParseException {
        JSONObject returnObj = new JSONObject();

        String openId = getSession(session);

        if(Utils.isBlank(openId)){
            return setReturnObjInfo("-100","没有登录");
        }
        String cid = request.getParameter("cid");
        String key = redisUtil.formatRedisKey(TEACHER_GET_LEAVE_INFO_LIST,openId,cid);

        JSONObject LeaveInfoList =  redisUtil.getJson(key);
        if(LeaveInfoList ==null){
            LeaveInfoList = teacherService.getLeaveList(cid,openId);
            redisUtil.set(key, LeaveInfoList.toString(), 500L);
        }
        returnObj.put("suc","100");
        returnObj.put("LeaveInfo",LeaveInfoList);
        return returnObj;
    }

    /**
     * 教师处理请假信息
     */
    @RequestMapping(value = "/doHandlerLeave" ,produces="text/html;charset=UTF-8")
    @ResponseBody
    public JSONObject doHandlerLeave(HttpSession session, HttpServletRequest request){
        JSONObject returnObj = new JSONObject();

        String openId = getSession(session);

        if(Utils.isBlank(openId)){
            return setReturnObjInfo("-100","没有登录");
        }
        HashMap leaveInfo = new HashMap<String,String>();
        String logId = request.getParameter("logId");
        String cid = request.getParameter("cid");
        leaveInfo.put("logId",logId);
        //教师操作信息  1 表示同意请假 2表示不同意请假
        String type = request.getParameter("type");
        leaveInfo.put("state",type);
        if(type.equals("2")){
            String remarks = request.getParameter("remarks");
            if(Utils.isBlank(remarks)){
                returnObj.put("fail","请输入不同意审批原因");
                return returnObj;
            }
            leaveInfo.put("remarks",remarks);
        }else{
            leaveInfo.put("remarks","同意");
        }
        //删除缓存
        String key = redisUtil.formatRedisKey(TEACHER_GET_LEAVE_INFO_LIST,openId,cid);
        redisUtil.remove(key);
        teacherService.updateLeaveState(leaveInfo,cid);
        returnObj.put("suc","100");
        return returnObj;
    }


    /**
     * 签到页面实时刷新
     * */
    @RequestMapping(value = "/updateSignInPage" ,produces="text/html;charset=UTF-8")
    @ResponseBody
    public JSONObject updateSignInPage(HttpSession session, HttpServletRequest request){
        JSONObject returnObj = new JSONObject();

        String cid = request.getParameter("cid");
        String type = request.getParameter("type");

        String key = redisUtil.formatRedisKey(CLASS_SIGN_KEY,cid,type);
        if(!redisUtil.exists(key)){
            returnObj.put("noSignInTime","不在签到时间");
            return returnObj;
        }
        //返回用户修改状态
        returnObj.put("info",teacherService.getUserSignInfo(cid));

        return returnObj;
    }

    /**
     * 老师导出某一次的签到记录具体信息表
     * */
    @RequestMapping(value = "/exportSignInList" ,produces="text/html;charset=UTF-8")
    @ResponseBody
    public Workbook  exportSignInList(HttpSession session, HttpServletRequest request, HttpServletResponse response){

        String openId = getSession(session);

        if(Utils.isBlank(openId)){
            return null;
        }

        String cid = request.getParameter("cid");
        String number = request.getParameter("number");

        JSONObject result = teacherService.getClassInfo(cid);

        OutputStream ouputStream = null;
        Workbook wb =null;
        try {
             wb = teacherService.exportSignInList(cid,number);
            setResponse(request,response,result.getString("name")+"第"+number+"次签到"+".xlsx");
            ouputStream = response.getOutputStream();
            wb.write(ouputStream);
            ouputStream.flush();
        } catch (Exception e) {
            logger.error("[queryExportUser]异常", e);
        } finally {
            if (ouputStream != null) {
                try {
                    ouputStream.close();
                } catch (IOException e) {
                    logger.error("[queryExportUser]输出流关闭异常", e);
                }
            }
        }
       return wb;
    }

   /**
    * 老师根据cid来导出本门课程的全部签到记录
    * */
   @RequestMapping(value = "/exportSignInListAllClass" ,produces="text/html;charset=UTF-8")
   @ResponseBody
   public Workbook  exportSignInListAllClass(HttpSession session, HttpServletRequest request, HttpServletResponse response){
       String openId = getSession(session);

       if(Utils.isBlank(openId)){

       }

       String cid = request.getParameter("cid");
       JSONObject result = teacherService.getClassInfo(cid);

       OutputStream ouputStream = null;
       Workbook wb =null;
       try {
           wb = teacherService.exportSignInListAllClass(cid);
           setResponse(request,response,result.getString("name")+"总签到记录表"+".xlsx");
           ouputStream = response.getOutputStream();
           wb.write(ouputStream);
           ouputStream.flush();
       } catch (Exception e) {
           logger.error("[queryExportUser]异常", e);
       } finally {
           if (ouputStream != null) {
               try {
                   ouputStream.close();
               } catch (IOException e) {
                   logger.error("[queryExportUser]输出流关闭异常", e);
               }
           }
       }
       return wb;
   }
    public static void setResponse(HttpServletRequest request,HttpServletResponse response,String filename) throws Exception{
        String userAgent = request.getHeader("User-Agent");
        if(userAgent.toLowerCase().contains("firefox")){
            filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1");
        }else{
            filename = URLEncoder.encode(filename, "UTF-8");
        }
        response.setContentType(request.getServletContext().getMimeType(filename));
        response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", filename));
    }

    public String getSession(HttpSession session){
        String openid = (String) session.getAttribute("openId");
        if(Utils.isNotBlank(openid)){
            return openid;
        }
        return null;
    }

    public static JSONObject setReturnObjInfo(String resCode, String resInfo) {
        JSONObject result = new JSONObject();
        result.put("resCode",resCode);
        result.put("resInfo",resInfo);
        return result;
    }

    @RequestMapping(value = "/getTeacherInfo" ,produces="text/html;charset=UTF-8")
    @ResponseBody
    public JSONObject getTeacherInfo(HttpSession session, HttpServletRequest request){
        JSONObject returnObj = new JSONObject();

        String openId = getSession(session);
        if(Utils.isBlank(openId)){
            return setReturnObjInfo("-100","没有登录");
        }
        returnObj.put("info",teacherService.getUserInfo(openId));

        returnObj.put("suc","100");
        return returnObj;
    }

    @RequestMapping(value = "/updateTeacherInfo" ,produces="text/html;charset=UTF-8")
    @ResponseBody
    public JSONObject updateTeacherInfo(HttpSession session, HttpServletRequest request) {
        JSONObject returnObj = new JSONObject();

        String openId = getSession(session);
        if (Utils.isBlank(openId)) {
            return setReturnObjInfo("-100", "没有登录");
        }
        //修改教师姓名
        String name = request.getParameter("name");
        boolean flag =  teacherService.updateUserInfo(name, openId);
        returnObj.put("suc","100");
        return returnObj;
    }

    @RequestMapping(value = "/getClassStudent" ,produces="text/html;charset=UTF-8")
    @ResponseBody
    public JSONObject getClassStudent(HttpSession session, HttpServletRequest request) {
        JSONObject returnObj = new JSONObject();

        String openId = getSession(session);
        if (Utils.isBlank(openId)) {
            return setReturnObjInfo("-100", "没有登录");
        }

        String cid = request.getParameter("cid");
        String page = request.getParameter("page");

        String key  = redisUtil.formatRedisKey(CLASSMEMBER,cid);
        if(redisUtil.exists(key)){
            JSONObject info = redisUtil.getJson(key);
             returnObj=teacherService.getPageClassStudent(info,Integer.parseInt(page));
             returnObj.put("pageLenth",info.getString("pageLenth"));
            return returnObj;
        }
        JSONObject result = new JSONObject();
        result.put("info",teacherService.getClassStudent(cid));
        result.put("pageLenth",result.getJSONArray("info").size()/10+1);
        redisUtil.set(key,result.toString(),5000L);
        returnObj=teacherService.getPageClassStudent(result,Integer.parseInt(page));
        returnObj.put("pageLenth",result.getString("pageLenth"));
        return returnObj;
    }


}
